package kr.hkit.powerjava.chapter23;

class Counter {
	private int value;

	public synchronized void increment() {
		value++;
	}

	public synchronized void decrement() {
		value--;
	}

	public synchronized void prnCounter() {
		System.out.println(value);
	}
}

class SharedMythread extends Thread {
	Counter sharedcConter;

	public SharedMythread(Counter sharedcConter) {
		this.sharedcConter = sharedcConter;
		start();
	}

	@Override
	public void run() {
		int i = 0;
		while (i < 20000) {
			sharedcConter.increment();
			sharedcConter.decrement();
			if (i % 40 == 0) {
				sharedcConter.prnCounter();
				try {
					sleep((int) (Math.random() * 2));

				} catch (InterruptedException e) {
				}
			}
			i++;
		}
	}
}

public class CountTest {
	public static void main(String[] args) {
		Counter c = new Counter();
		new SharedMythread(c);
		new SharedMythread(c);
		new SharedMythread(c);
		new SharedMythread(c);
	}
}
